
global root_dir = "`1'"

include "$root_dir/code/config/config.do"


cap noi log using ${log_dir}/biadic_families.log, replace name(dat)

*Handle empty arguments
global arg1 = cond("`2'" == "___EMPTY___", "", "`2'")
global arg2 = cond("`3'" == "___EMPTY___", "", "`3'")
global arg3 = cond("`4'" == "___EMPTY___", "", "`4'")
global arg4 = cond("`5'" == "___EMPTY___", "", "`5'")

if "$arg1" != "" {
    global weight_category "$arg1"
    di "Weight category: ${weight_category}"
}

if "$arg2" != "" {
    global weight_versions "$arg2"
    di "Weight versions: ${weight_versions}"
}

if "$arg3" != "" {
    global weight_window "$arg3"
    di "Weight window: ${weight_window}"
}

if "$arg4" != "" {
	global wtype "$arg4"
}
di "${wtype}"

capture noi {


* biadic_families.do
*********************************************************************************
* This do-file flags patent families that are applied for in multiple countries.*
*********************************************************************************

use ${commondata_dir}/patstat_2018b/appln_info.dta, clear
replace appln_auth = upper(appln_auth)

gen ep = appln_auth == "EP"
gen us = appln_auth == "US"
gen jp = appln_auth == "JP"
gen de = appln_auth == "DE"
gen fr = appln_auth == "FR"
gen gb = appln_auth == "GB"

mmerge appln_id using ${commondata_dir}/patstat_2018b/family_info.dta, ukeep(docdb_family_id)
drop _m

egen tag = tag(docdb_family_id appln_auth)
egen fam_numdistinctuauth = total(tag), by(docdb_family_id)
drop tag

keep docdb_family_id fam_numdistinctuauth 
duplicates drop

*get biadic families
gen biadic_D = fam_numdistinctuauth >= 2

keep docdb_family_id biadic_D
mmerge docdb_family_id using ${commondata_dir}/patstat_2018b/docdb_families.dta, unmatched(master) ukeep(hvi)
drop _m
compress

*labeling¨
label var biadic_D "Biadic family across all countries"
label var docdb_family_id "Patent Family ID"

save ${dataset_dir}/patstat_orbis/docdb_families2.dta, replace

}
if _rc == 0 {
    display "Execution finished successfully."
}
else {
    display "Execution finished with errors."
}

cap log close dat